package com.atjinggu.jinggumail.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atjinggu.jinggumail.cart.feign.ProductFeignService;
import com.atjinggu.jinggumail.cart.interceptor.CartInterceptor;
import com.atjinggu.jinggumail.cart.service.CartService;
import com.atjinggu.jinggumail.cart.vo.Cart;
import com.atjinggu.jinggumail.cart.vo.CartItem;
import com.atjinggu.jinggumail.cart.vo.CartSkuInfoVo;
import com.atjinggu.jinggumail.cart.vo.UserInfoTo;
import com.atjinggu.jinggumail.common.utils.R;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import net.sf.jsqlparser.expression.ValueListExpression;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author jingming
 * @Type CartServiceImpl.java
 * @Desc
 * @date 2021/3/5 16:29
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_ITEM_KEY = "jinggumail:cart:";



    @Override
    public CartItem addToCart(String skuId, Integer count) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String skuInfoStr = (String) ops.get(skuId);
        if(StringUtils.isEmpty(skuInfoStr)) {
            CartItem item = new CartItem();
            item.setCheck(true);
            item.setCount(count);
            item.setSkuId(skuId);
            CompletableFuture<Void> skuFuture = CompletableFuture.runAsync(() -> {
                R info = productFeignService.info(Long.parseLong(skuId));
                CartSkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<CartSkuInfoVo>() {
                });
                item.setImage(skuInfo.getSkuDefaultImg());
                item.setPrice(skuInfo.getPrice());
                item.setTitle(skuInfo.getSkuTitle());
            }, executor);
            CompletableFuture<Void> saleAttrFuture = CompletableFuture.runAsync(() -> {
                List<String> attrs = productFeignService.getSaleAttrListString(skuId);
                item.setSaleAttr(attrs);
            }, executor);
            CompletableFuture.allOf(skuFuture, saleAttrFuture).get();
            ops.put(skuId, JSON.toJSONString(item));
            return item;
        }else {
            CartItem item = JSON.parseObject(skuInfoStr, CartItem.class);
            item.setCount(item.getCount() + count);
            ops.put(skuId,JSON.toJSONString(item));
            return item;
        }


    }

    @Override
    public CartItem getCartSkuInfo(String skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String  str = (String) ops.get(skuId);
        CartItem item = JSON.parseObject(str, CartItem.class);
        return item;
    }


    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(StringUtils.isNotEmpty(userInfoTo.getUserId())){
            cartKey = CART_ITEM_KEY + userInfoTo.getUserId();
        }else {
            cartKey = CART_ITEM_KEY + userInfoTo.getUserKey();
        }
        return  redisTemplate.boundHashOps(cartKey);
    }


    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tmpCartKey = CART_ITEM_KEY + userInfoTo.getUserKey();
        BoundHashOperations<String, Object, Object> tmpOps = redisTemplate.boundHashOps(tmpCartKey);
        if(StringUtils.isNotEmpty(userInfoTo.getUserId())){
            List<Object> values = tmpOps.values();
            if(CollectionUtils.isNotEmpty(values)) {
                for (Object value : values) {
                    String str = (String) value;
                    CartItem cartItem = JSON.parseObject(str, CartItem.class);
                    addToCart(cartItem.getSkuId(), cartItem.getCount());

                }
            }
            String cartKey = CART_ITEM_KEY + userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
            List<Object> vals = ops.values();
            List<CartItem> collect = vals.stream().map(item -> {
                String str = (String) item;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            cart.setCartItems(collect);
            redisTemplate.delete(tmpCartKey);
            return cart;
        }else {
            List<Object> values = tmpOps.values();
            if(CollectionUtils.isNotEmpty(values)) {
                List<CartItem> collect = values.stream().map(item -> {
                    String str = (String) item;
                    return JSON.parseObject(str, CartItem.class);
                }).collect(Collectors.toList());
                cart.setCartItems(collect);
            }
            return cart;
        }
    }

    @Override
    public void checkItem(String skuId, Integer check) {
        CartItem cartSkuInfo = getCartSkuInfo(skuId);
        cartSkuInfo.setCheck(check==1);
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.put(skuId,JSON.toJSONString(cartSkuInfo));
    }

    @Override
    public void changeItemCount(String skuId, Integer num) {
        CartItem cartSkuInfo = getCartSkuInfo(skuId);
        cartSkuInfo.setCount(num);
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.put(skuId,JSON.toJSONString(cartSkuInfo));
    }

    @Override
    public void deleteItem(String skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        ops.delete(skuId);
    }

    @Override
    public List<CartItem> OrderItemList() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(StringUtils.isEmpty(userInfoTo.getUserId() )){
            return null;
        }
        String  cartKey = CART_ITEM_KEY + userInfoTo.getUserId();
        BoundHashOperations<String, Object, Object> ops =  redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        List<CartItem> collect = null;
        if(CollectionUtils.isNotEmpty(values)) {
            collect = values.stream().map(item -> {
                String str = (String) item;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                R info = productFeignService.info(Long.parseLong(cartItem.getSkuId()));
                CartSkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<CartSkuInfoVo>() {
                });
                cartItem.setPrice(skuInfo.getPrice());
                return cartItem;
            }).filter(item -> item.getCheck()).collect(Collectors.toList());
        }
        return collect;
    }


}